//搜索
#pragma once


#include"index.hpp"
#include"util.hpp"
#include<algorithm>
#include<unordered_map>
#include<jsoncpp/json/json.h>

namespace ns_sercher
{
    //倒排打印
   struct InvertedElemPrint
    {
        uint64_t doc_id;//文档唯一标示符
        int weight;//权值
        std::vector<std::string> words;//存储关键词
        InvertedElemPrint()
        :doc_id(0),
        weight(0)
        {}
    };
    //搜索
    class Searcher
    {
        private:
        ns_index::Index *index;//共系统进行查找的索引；
        public:
        Searcher()
        {}
        ~Searcher()
        {}
        public:
        //初始化
            void InitSearchar(const std::string &input)
            {
                //创建/获取index对象
                index = ns_index::Index::GetInstance();
                LOG(NORMAL,"获取index单例成功...");
                index->BuildIndex(input);
                LOG(NORMAL,"建立正排和倒排索引成功...");
            }
        //query:搜索关键字
        //json_string：返回给用户浏览器的搜索结果
        //搜索
        void Search(const std::string &query,std::string *Json_string)
        {
            //分词按照关键字进行，
            std::vector<std::string> words;
            ns_util::JiebaUtil::CutString(query,&words);
            //触发：根据分词的各个词进行index查找，建立index是忽略大小写，大写转换为小写
            //ns_index::InvertedElem inverted_list_all;内部invertedElem
            std::vector<InvertedElemPrint> inverted_list_all;
            std::unordered_map<uint64_t,InvertedElemPrint> tokens_map;//映射
            for(std::string word:words)
            {
                boost::to_lower(word);//大写转小写
                //创建倒排拉链对象，获取倒排拉链
                ns_index::InvertedList *inverted_list = index->GetInvertedList(word);
                if(nullptr ==inverted_list)
                {
                    continue;
                }
                for(const auto &elem : *inverted_list)
                {
                    auto &item = tokens_map[elem.doc_id];//存在获取，不存在就创建
                    //iter是doc_id相同的print节点
                    item.doc_id= elem.doc_id;
                    item.weight+=elem.weight;
                    item.words.push_back(elem.word);
                }
            }
            for(const auto &item :tokens_map)
            {
                inverted_list_all.push_back(std::move(item.second));
            }
            //合并排序::汇总擦护照结果，按照相关性(权重)降序排序//sort
            std::sort(inverted_list_all.begin(),inverted_list_all.end(),\
                    [](const InvertedElemPrint &e1,const InvertedElemPrint &e2){
                        return  e1.weight>e2.weight;
                    });
            //构建 根据查出来的结果，构建json传 通过jsoncpp完成序列化和反序列化
            Json::Value root;
            for(auto &item:inverted_list_all)
            {
                ns_index::DocInfo *doc = index->GetForwardIndex(item.doc_id);
                if(doc==nullptr)
                {
                    continue;
                }
                Json::Value elem;
                elem["title"] = doc->title;
                elem["desc"]=GetDesc(doc->content,item.words[0]);//单词
                elem["url"] = doc->url;
                elem["id"] = (int)item.doc_id;
                elem["weight"]=item.weight;

                root .append(elem);
            }
            Json::FastWriter writer;
            *Json_string = writer.write(root);
        }
        //获取关键字描述
        std::string GetDesc(const std::string &html_content,const std::string &word)
        {
            //找到词在html_content中的首次出现，然后向前找50字节如果没有从begin开始，向后找100字节，
            //如果没有到end结束
            //获取出之间的内容
            const int prev_step = 50;
            const int next_step = 100;
            //找到首次出现
            auto iter =std::search(html_content.begin(),html_content.end(),word.begin(),word.end(),[](int x,int y){
            return (std::tolower(x) == std::tolower(y));
            });
            if(iter == html_content.end())
            {
                return "none1";
            }
            int pos = std::distance(html_content.begin(),iter);
            //获取staet ,end 
            int start = 0;
            int end=html_content.size()-1;
            //如果之前有50多就更形开始位置
            if(pos>start+prev_step)
            {
                start = pos - prev_step;
            }
            if(pos<end-next_step)
            {
                end=pos+next_step;
            }
            //截取字串 return
            if(start>=end)
            {
                return "None2";
            }
            std::string desc = html_content.substr(start,end - start);
            desc+="...";
            return desc;
        }
    };
}